package com.example.redis.demo.annotations;

import com.example.redis.demo.exception.BusinessException;
import com.example.redis.demo.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Component
public class WebControllerAnnotationHandler extends HandlerInterceptorAdapter {


    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            // 配置该注解，说明不进行用户拦截
            RequireAuth annotation = handlerMethod.getMethodAnnotation(RequireAuth.class);
            if (annotation != null) {
                //需要鉴权
                boolean required = annotation.required();
                if (required) {
                    String xToken = request.getHeader("x-token");
                    if (xToken == null) {
                        throw BusinessException.errorOfCode("需要传递用户token", "401");
                    }
                    Map<String, Object> claims = JwtUtil.parseToken(xToken);
                    Long id = Long.valueOf(claims.get("id").toString());
                    ValueOperations<String, Object> valueOperations = this.redisTemplate.opsForValue();
                    String accessToken = (String) valueOperations.get("u:" + id + ":access_token");
                    if (accessToken == null) {
                        throw BusinessException.errorOfCode("用户不存在", "401");
                    }
                }
                return super.preHandle(request, response, handler);
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        super.afterCompletion(request, response, handler, ex);
    }
}
